package repository

import (
	"fitness/go-admin/internal/model"

	"gorm.io/gorm"
)

type PlanRepository interface {
	Create(plan *model.Plan) error
	Update(plan *model.Plan) error
	Delete(id uint) error
	GetByID(id uint) (*model.Plan, error)
	List(page, pageSize int) ([]model.Plan, int64, error)
	ListByMemberID(memberID uint, page, pageSize int) ([]model.Plan, int64, error)
}

type planRepository struct {
	db *gorm.DB
}

func NewPlanRepository(db *gorm.DB) PlanRepository {
	return &planRepository{db: db}
}

func (r *planRepository) Create(plan *model.Plan) error {
	return r.db.Create(plan).Error
}

func (r *planRepository) Update(plan *model.Plan) error {
	return r.db.Save(plan).Error
}

func (r *planRepository) Delete(id uint) error {
	return r.db.Delete(&model.Plan{}, id).Error
}

func (r *planRepository) GetByID(id uint) (*model.Plan, error) {
	var plan model.Plan
	err := r.db.First(&plan, id).Error
	return &plan, err
}

func (r *planRepository) List(page, pageSize int) ([]model.Plan, int64, error) {
	var plans []model.Plan
	var total int64

	offset := (page - 1) * pageSize

	if err := r.db.Model(&model.Plan{}).Count(&total).Error; err != nil {
		return nil, 0, err
	}

	err := r.db.Offset(offset).Limit(pageSize).Order("created_at DESC").Find(&plans).Error
	return plans, total, err
}

func (r *planRepository) ListByMemberID(memberID uint, page, pageSize int) ([]model.Plan, int64, error) {
	var plans []model.Plan
	var total int64

	offset := (page - 1) * pageSize

	query := r.db.Model(&model.Plan{}).Where("member_id = ?", memberID)

	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	err := query.Offset(offset).Limit(pageSize).Order("created_at DESC").Find(&plans).Error
	return plans, total, err
}
